package com.xinfan.mhl.dao;

import com.xinfan.mhl.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author xin
 * @Date 2022/6/22 23:20
 * @Version 1.0
 */
public class BasicDao<T> {
    private QueryRunner qr = new QueryRunner();

    public int update(String sql,Object... parameters) {
        Connection connection = JDBCUtilsByDruid.getConnection();
        try {
            return qr.update(connection, sql, parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<T> selectMany(String sql,Class<T> clazz,Object... parameters) {
        Connection connection = JDBCUtilsByDruid.getConnection();
        try {
            return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public T selectOne(String sql,Class<T> clazz, Object... parameters) {
        Connection connection = JDBCUtilsByDruid.getConnection();
        try {
            return qr.query(connection, sql, new BeanHandler<>(clazz), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Object selectScalar(String sql,Object... parameters) {
        Connection connection = JDBCUtilsByDruid.getConnection();
        try {
            return qr.query(connection, sql, new ScalarHandler(), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
